package org.smile.strate;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
/**
 * Action 的父类 所有的action必须继承此类
 * @author strive
 *
 */
public class ActionSupport implements Action {
	
	protected static final Logger logger=Logger.getLogger(ActionSupport.class);
	/**
	 * 字体编码
	 */
	protected String encode="UTF-8";
	/**
	 * request对象
	 */
	protected HttpServletRequest request;
	/**
	 * response对象
	 */
	protected HttpServletResponse response;
	/**
	 * 提交类型
	 */
	protected int type;
	/**
	 * 初始化Actoin信息
	 * @param request
	 * @param response
	 * @param type
	 * @param encode
	 */
	public void initPerterties(HttpServletRequest request,HttpServletResponse response,Integer type,String encode){
		this.type=type;
		this.request=request;
		this.response=response;
		this.encode=encode;
	}
	/**
	 * 获取参数值
	 * @param paramName
	 * @return
	 */
	protected String getParamter(String paramName){
		return request.getParameter(paramName);
	}
	/**
	 * 获取参数值 编码是ISO8859-1的参数
	 * 常用于GET提交时
	 * @param paramName
	 * @return
	 */
	protected String getParamterISO88591(String paramName){
		try {
			return new String(request.getParameter(paramName).getBytes("ISO-8859-1"),encode);
		} catch (UnsupportedEncodingException e) {
			return request.getParameter(paramName);
		}
	}
	/**
	 * 打印一个字符串到response中
	 * @param str
	 * @throws IOException
	 */
	protected void printString(String str) throws IOException{
		response.setCharacterEncoding(encode);
		response.setContentType("text/html");
		PrintWriter pw=null;
		try{
			pw=response.getWriter();
			pw.print(str);
		}finally{
			pw.close();
		}
	}
	/**
	 * 服务器跳转
	 * @param url 跳转路径
	 * @throws ServletException
	 */
	protected void forward(String url) throws ServletException{
		try{
			request.getRequestDispatcher(url).forward(request, response);
			
		}catch(Exception e){
			throw new ServletException("服务器跳转 forward to "+url+"出现错误",e);
		}
	}
	/**
	 * 重定向跳转
	 * @param url 重定向路径
	 * @throws IOException 
	 */
	protected void redirect(String url) throws IOException{
		response.sendRedirect(url);
	}
	
	public String getEncode() {
		return encode;
	}
	public HttpServletRequest getRequest() {
		return request;
	}
	public HttpServletResponse getResponse() {
		return response;
	}
	public int getType() {
		return type;
	}
}
